<template>
  <div class="app-container">
    <el-card>
      <el-page-header @back="goBack">
        <template #content>
          <div class="flex items-center">
            <div v-if="!route.query?.id">新增纸张出库单</div>
            <div v-else>
              <span
                class="text-sm mr-2"
                style="color: var(--el-text-color-regular)"
              >
                纸张出库单编码:
              </span>
              <el-tag>{{ form.outboundCode }}</el-tag>
            </div>
          </div>
        </template>
        <template #extra>
          <div class="flex items-center" v-if="!route.query.info">
            <el-button type="primary" :loading="btnLoading" @click="submitForm"
              >保 存</el-button
            >
          </div>
        </template>
      </el-page-header>
    </el-card>
    <el-card style="margin-top: 10px">
      <el-collapse v-model="activeNames">
        <el-collapse-item disabled title="基本信息" name="1">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">基本信息</span>
          </template>
          <div>
            <el-form
              :model="form"
              :rules="rules"
              :disabled="flag"
              ref="userRef"
              label-width="100px"
            >
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="出库人" prop="outboundName">
                    <el-input
                      v-model="form.outboundName"
                      readonly
                      placeholder=""
                      maxlength="18"
                    />
                  </el-form-item>
                </el-col>
                <!-- <el-col :span="8">
                                    <el-form-item label="出库机台" prop="machineName">
                                        <el-input
                                            v-model="form.machineName"
                                            readonly
                                            placeholder="请选择机台"
                                            @click="openDialog"
                                        />
                                    </el-form-item>
                                </el-col> -->
                <!-- <el-col :span="8">
                                    <el-form-item label="车间" prop="workshopName">
                                        <el-input
                                            v-model="form.workshopName"
                                            readonly
                                            placeholder="自动带出"
                                        />
                                    </el-form-item>
                                </el-col> -->
                <el-col :span="8">
                  <el-form-item label="出库时间" prop="outboundDate">
                    <el-date-picker
                      style="width: 100%"
                      v-model="form.outboundDate"
                      format="YYYY-MM-DD HH:mm:ss"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      type="datetime"
                      placeholder="请选择时间"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="创建人" prop="createBy">
                    <el-input v-model="form.createBy" readonly placeholder="" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="创建时间" prop="createTime">
                    <el-date-picker
                      style="width: 100%"
                      readonly
                      v-model="form.createTime"
                      format="YYYY-MM-DD HH:mm:ss"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      type="datetime"
                      placeholder="请选择时间"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="备注">
                    <el-input
                      v-model="form.remark"
                      type="textarea"
                      placeholder="请输入内容"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-collapse-item>
        <el-collapse-item disabled title="出库明细" name="2">
          <template #title>
            <el-icon style="color: #4479f6">
              <Position />
            </el-icon>
            <span class="title">出库明细</span>
          </template>
          <el-button
            v-if="!flag"
            style="margin-bottom: 10px"
            type="primary"
            size="small"
            @click="handleAddStorage"
          >
            选择纸张
          </el-button>
          <el-table
            v-loading="loading"
            class="table-form"
            :data="mesCuttingOutboundDetails"
          >
            <el-table-column
              label="序号"
              width="60"
              type="index"
              align="center"
            ></el-table-column>
            <!--                        <el-table-column label="订单编码" align="center" :show-overflow-tooltip="true" prop="orderNo">-->
            <!--                        </el-table-column>-->
            <el-table-column
              label="纸张编码"
              align="center"
              min-width="160"
              prop="code"
            ></el-table-column>
            <el-table-column
              label="纸张名称"
              align="center"
              min-width="160"
              prop="name"
            ></el-table-column>
            <el-table-column label="规格" align="center" prop="specs">
              <!-- <template #default="scope">
                                <dict-tag :options="mes_paper_specs" :value="scope.row.specs" />
                            </template> -->
              <template #default="scope">
                <span v-if="scope.row.longWide">
                  {{ scope.row.longWide }}
                </span>
                <span v-if="scope.row.specs">
                  <dict-tag
                    :options="mes_paper_specs"
                    :value="scope.row.specs"
                  />
                </span>
              </template>
            </el-table-column>
            <el-table-column
              label="定量"
              align="center"
              prop="weight"
            ></el-table-column>
            <el-table-column label="品牌" align="center" prop="brand">
              <template #default="scope">
                <dict-tag :options="mes_paper_brand" :value="scope.row.brand" />
              </template>
            </el-table-column>
            <el-table-column label="纸型" align="center" prop="paperType">
              <template #default="scope">
                <dict-tag
                  :options="mes_paper_type"
                  :value="scope.row.paperType"
                />
              </template>
            </el-table-column>
            <!-- <el-table-column
                            label="幅宽"
                            align="center"
                            prop="longWide"
                        ></el-table-column> -->
            <!-- <el-table-column
                            label="宽度"
                            align="center"
                            :show-overflow-tooltip="true"
                            prop="wide"
                        ></el-table-column> -->
            <el-table-column
              label="单位"
              align="center"
              :show-overflow-tooltip="true"
              prop="unit"
            >
              <template #default="scope">
                <dict-tag :options="mes_paper_unit" :value="scope.row.unit" />
              </template>
            </el-table-column>
            <el-table-column align="center" min-width="120" prop="lnumber">
              <template #header>
                <div>
                  令/件
                  <br />
                  kg/卷筒
                </div>
              </template>
              <template #default="scope">
                <el-form-item>
                  <el-input
                    type="number"
                    :disabled="flag"
                    @blur="changeSumTotal(scope.row, scope.$index)"
                    v-model="scope.row.lnumber"
                    placeholder="请输入"
                  ></el-input>
                  <!-- v-model.number)-->
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" min-width="120" prop="jnumber">
              <template #header>
                <div>
                  件数
                  <br />
                  卷筒数
                </div>
              </template>
              <template #default="scope">
                <el-form-item>
                  <el-input
                    type="number"
                    :disabled="flag"
                    @blur="changeSumTotal(scope.row, scope.$index)"
                    v-model="scope.row.jnumber"
                    placeholder="请输入"
                  ></el-input>
                  <!--v-model.number-->
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column align="center" min-width="120" prop="odd">
              <template #header>
                <div>
                  零头(令)
                  <br />
                  零头(kg)
                </div>
              </template>
              <template #default="scope">
                <el-form-item>
                  <el-input
                    type="number"
                    v-model="scope.row.odd"
                    :disabled="flag"
                    @blur="changeSumTotal(scope.row, scope.$index)"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <!-- <el-table-column
                            align="center"
                            label="需用数量"
                            min-width="120"
                            prop="needNumber"
                            :show-overflow-tooltip="true"
                        ></el-table-column> -->
            <el-table-column
              align="center"
              label="库存数量"
              min-width="120"
              prop="inventoryNumber"
              :show-overflow-tooltip="true"
              v-if="false"
            ></el-table-column>
            <el-table-column
              align="center"
              label="出库数量"
              min-width="120"
              prop="outboundNumber"
              :show-overflow-tooltip="true"
            >
              <template #default="scope">
                <!-- @change="SumAmount(scope.row)" -->
                <el-form-item>
                  <el-input
                    @input="limitInput('outboundNumber', scope.row)"
                    type="number"
                    :disabled="flag"
                    v-model="scope.row.outboundNumber"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="备注"
              width="120"
              align="center"
              prop="useRemark"
              :show-overflow-tooltip="true"
            >
              <template #default="scope">
                <span v-if="flag">{{ scope.row.remark }}</span>
                <el-form-item v-else>
                  <el-input
                    v-model="scope.row.remark"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              v-if="!flag"
              align="center"
              fixed="right"
              class-name="small-padding fixed-width"
            >
              <template #default="scope">
                <el-tooltip content="删除" placement="top">
                  <el-button
                    link
                    type="primary"
                    icon="Delete"
                    @click="handleDelete(scope.row)"
                  ></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
      </el-collapse>
    </el-card>
    <SearchWorkBench
      :visible="searchVisible"
      @changeUpdate="changeWorkBenchData"
      :machineType="5"
      @cancel="
        () => {
          searchVisible = false;
        }
      "
    ></SearchWorkBench>
    <!-- 纸张选择 -->
    <SearchPaperS
      :visible="paperVisible"
      @changeUpdate="changeData"
      :count="true"
      :search="{ packageType: 1, quantity: 1 }"
      @cancel="
        () => {
          paperVisible = false;
        }
      "
      :paperSelectList="paperSelectList"
    ></SearchPaperS>
  </div>
</template>

<script setup>
import SearchWorkBench from "@/components/SearchWorkBench";
import SearchPaperS from "@/components/SearchPaperS";
import orderList from "./orderList.vue";
import { toNumber } from "@/utils/ruoyi";
import {
  addOutboundInfo,
  getOutboundInfo,
} from "@/api/storage/paperOutBound.js";
import useTagsViewStore from "@/store/modules/tagsView";
import useUserStore from "@/store/modules/user";
import { ElMessage } from "element-plus";
import { nextTick } from "vue";
const tagsViewStore = useTagsViewStore();
const { proxy } = getCurrentInstance();
const { mes_paper_specs, mes_paper_type, mes_paper_unit, mes_paper_brand } =
  proxy.useDict(
    "mes_paper_specs",
    "mes_paper_type",
    "mes_paper_unit",
    "mes_paper_brand"
  );
const route = useRoute();
const router = useRouter();
const searchVisible = ref(false);
const paperSelectList = ref([]);
const activeNames = ["1", "2"];
const userRef = ref(null);
const flag = ref(false);
const loading = ref(false);
const btnLoading = ref(false);
const paperVisible = ref(false);
const userInfo = useUserStore();
const data = reactive({
  form: {},
  mesCuttingOutboundDetails: [],
  rules: {
    machineName: [
      { required: true, message: "出库机台不能为空", trigger: "change" },
    ],
    // outboundDate: [{ required: true, message: "出库时间不能为空", trigger: ["blur", "change"] }],
  },
});

const { form, rules, mesCuttingOutboundDetails } = toRefs(data);

//限制只能输入4位小数
function limitInput(key, row) {
  row[key] =
    ("" + row[key]) // 第一步：转成字符串
      .replace(/[^\d^\.]+/g, "") // 第二步：把不是数字，不是小数点的过滤掉
      .replace(/^0+(\d)/, "$1") // 第三步：第一位0开头，0后面为数字，则过滤掉，取后面的数字
      .replace(/^\./, "0.") // 第四步：如果输入的第一位为小数点，则替换成 0. 实现自动补全
      .match(/^\d*(\.?\d{0,4})/g)[0] || ""; // 第五步：最终匹配得到结果 以数字开头，只有一个小数点，	而且小数点后面只能有0到2位小数
}
nextTick(() => {
  form.value.createBy = userInfo.name;
  form.value.outboundName = userInfo.name;
});

if (route.query.id) {
  getOutboundInfo(route.query.id).then((res) => {
    Object.assign(form.value, { ...res.data });
    mesCuttingOutboundDetails.value = res.data.mesCuttingOutboundDetails.map(
      (item) => {
        return {
          ...item,
          ...item.mesPaper,
          id: item.paperId,
        };
      }
    );
    if (route.query.info) {
      flag.value = true;
    }
  });
} else {
  flag.value = false;
  form.value = {};
  mesCuttingOutboundDetails.value = [];
}

const changeSumTotal = (row, index) => {
  // if (row.lnumber && row.jumber && row.odd) {
  const count =
    Number(row.lnumber ? row.lnumber : 0.0) *
      Number(row.jnumber ? row.jnumber : 0.0) +
    Number(row.odd ? row.odd : 0.0);
  mesCuttingOutboundDetails.value[index].outboundNumber = toNumber(count, 4);
  // }
};

// 获取当前时间
const getCurrentDateTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  const hours = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");
  form.value.createTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  form.value.outboundDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
getCurrentDateTime();

// 打开机台页面
const openDialog = () => {
  searchVisible.value = true;
};
// 选中的机台
const changeWorkBenchData = (row) => {
  form.value.machineName = row.machineName;
  form.value.machineId = row.pid;
  // form.value.workshopName = row.workshopName
  searchVisible.value = false;
};

// 新增出库明细
const handleAddStorage = () => {
  paperSelectList.value = mesCuttingOutboundDetails.value;
  paperVisible.value = true;
};
// 选中的入库明细
const changeData = (row) => {
  const codeSet = new Set(
    mesCuttingOutboundDetails.value.map((data) => data.id)
  );
  row.forEach((item) => {
    item.paperId = item.id;
    item.inventoryNumber = item.quantity;
    if (!codeSet.has(item.id)) {
      mesCuttingOutboundDetails.value.push({ ...item });
      codeSet.add(item.id);
    }
  });
  paperVisible.value = false;
};

// 删除
const handleDelete = (row) => {
  proxy.$modal.confirm("是否确认删除该数据？").then(function () {
    mesCuttingOutboundDetails.value = mesCuttingOutboundDetails.value.filter(
      (item) => (item.paperId ? item.paperId != row.id : item.id != row.id)
    );
    proxy.$modal.msgSuccess("删除成功");
  });
};
// const SumAmount = row => {
//     if (Number(row.outboundNumber) > row.inventoryNumber) {
//         row.outboundNumber = null
//         return ElMessage({
//             message: '出库数量不能大于库存数量',
//             type: 'warning',
//         })
//     }
// }
// 清除主键
const clearId = (list, key) => {
  if (list.length > 0) {
    list.forEach((item) => {
      delete item[key];
    });
  }
};
// 确认
const submitForm = () => {
  userRef.value.validate((valid) => {
    if (valid) {
      btnLoading.value = true;
      clearId(mesCuttingOutboundDetails.value, "id");
      if (route.query.id) {
        addOutboundInfo({
          ...form.value,
          mesCuttingOutboundDetails: mesCuttingOutboundDetails.value,
        })
          .then((res) => {
            ElMessage({
              message: "编辑成功",
              type: "success",
            });
            goBack();
          })
          .catch((err) => {
            btnLoading.value = true;
          });
      } else {
        addOutboundInfo({
          ...form.value,
          status: 1,
          mesCuttingOutboundDetails: mesCuttingOutboundDetails.value,
        })
          .then((res) => {
            ElMessage({
              message: "新增成功",
              type: "success",
            });
            goBack();
          })
          .catch((err) => {
            btnLoading.value = true;
          });
      }
    }
  });
};
//  返回
const goBack = () => {
  tagsViewStore.delView(route);
  router.go(-1);
  // router.push('/storage/paperAccess')
};
</script>

<style lang="scss" scoped>
.footer {
  text-align: center;
}

:deep(.el-pagination) {
  position: unset;
}

.table-form :deep(.el-form-item) {
  margin-bottom: 0;
}
</style>
